<script setup>
import { ref } from 'vue'
import { editChannelService, addChannelService } from '@/api/atricle.js'
const flag = ref(false)
const width = ref('100px')
const formModel = ref({
  cate_name: '',
  cate_alias: ''
})
const form = ref()
const rules = ref({
  cate_name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { patten: /^\S{1,10}$/, message: '长度在1到10之间', trigger: 'blur' }
  ],
  cate_alias: [
    { required: true, message: '请输入分类别名', trigger: 'blur' },
    { patten: /^\S[a-zA-Z]{1,10}$/, message: '长度在1到10之间', trigger: 'blur' }
  ]
})

const open = (obj) => {
  flag.value = true
  formModel.value = { ...obj }
}
const emit = defineEmits(['success'])
const onsubmit = async () => {
  await form.value.validate()
  const isEdit = formModel.value.id
  if (isEdit) {
    await editChannelService(formModel.value)
    ElMessage.success('修改成功')
  } else {
    await addChannelService(formModel.value)
    ElMessage.success('添加成功')
  }
  flag.value = false
  emit('success')
}

defineExpose({
  open
})
</script>
<template>
  <div>
    <el-dialog :title="formModel.id ? '编辑分类' : '添加分类'" v-model="flag" width="40%">
      <el-form ref="form" :model="formModel" :rules="rules">
        <el-form-item label="分类名称" :label-width="width" prop="cate_name">
          <el-input v-model="formModel.cate_name" />
        </el-form-item>
        <el-form-item label="分类别名" :label-width="width" prop="cate_alias">
          <el-input v-model="formModel.cate_alias" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="flag = false">取消</el-button>
          <el-button type="primary" @click="onsubmit">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped></style>